//
// Created by hjie on 23-6-22.
//

#include "server_manager.h"
#include "websocket_server.h"
#include "room_manager.h"
#include "signal_thread_pool.h"

ServerManager::ServerManager()
{

}
ServerManager::~ServerManager()
{
    Stop();
}

int ServerManager::Start()
{
    int port     = 3347;
    int ssl_port = 2347;

    m_room_manager = new RoomManager(this);

    m_port_server_map[port]     = new WebSocketServer();
    m_port_server_map[ssl_port] = new SSLWebSocketServer();

    m_signal_thread_pool = std::make_shared<SignalThreadPool>();

    for (auto & data : m_port_server_map)
    {
        m_thread_vec.push_back(std::thread(&WebSocket::StartListen, data.second, data.first));
    }

    m_signal_thread_pool->StartThread(10);

    m_main_thread = std::thread([this](){

        OnThread();
    });
    m_main_thread.join();
    return 0;
}

int ServerManager::Stop()
{
    for (auto & server : m_port_server_map)
    {
        server.second->StopServer();
    }
    m_port_server_map.clear();
    for (auto & thread : m_thread_vec)
    {
        if (thread.joinable())
        {
            thread.join();
        }
    }
    m_thread_vec.clear();
    m_signal_thread_pool->StopThread();
    return 0;
}

void ServerManager::OnThread()
{
    while(true)
    {
        m_room_manager->CheckIdleRoom();
        usleep(1000 * 1000);    // 1s
    }
}












